package userHelp

import (
	myConfig "common/config"
	"common/helper"
	myredis "common/redis"
	"fmt"
	"math"
	"strconv"
	"time"
)

/*
玩家流水处理
*/

/*
加载玩家最早未完成的一笔打码
*/

type MemberWageRequire struct {
	ID              int64   `json:"ID" db:"ID"`
	AddTime         string  `json:"AddTime" db:"AddTime"`
	Uid             int32   `json:"uid" db:"uid"`
	ChangeMoney     float64 `json:"ChangeMoney" db:"ChangeMoney"`
	NeedWageRequire float64 `json:"NeedWageRequire" db:"NeedWageRequire"`
	CurWageRequire  float64 `json:"CurWageRequire" db:"CurWageRequire"`
	Status          int     `json:"Status" db:"Status"`
	ChangeType      int     `json:"ChangeType" db:"ChangeType"`
}

var g_tbl_member_wage_require = "tbl_member_wage_require:"

var g_tbl_member_wage_require_next = "tbl_member_wage_require_next:"

/*
获取正在进行中的打码任务
*/
func GetCurWageReuqire(uid string) MemberWageRequire {
	var dataRet MemberWageRequire
	dataRet.ID = myredis.GetUserFieldInt64NoSelect(uid, g_tbl_member_wage_require+"ID")
	dataRet.ChangeMoney = myredis.GetUserFieldFloat64NoSelect(uid, g_tbl_member_wage_require+"ChangeMoney")
	dataRet.NeedWageRequire = myredis.GetUserFieldFloat64NoSelect(uid, g_tbl_member_wage_require+"NeedWageRequire")
	dataRet.CurWageRequire = myredis.GetUserFieldFloat64NoSelect(uid, g_tbl_member_wage_require+"CurWageRequire")
	dataRet.Status = int(myredis.GetUserFieldInt64NoSelect(uid, g_tbl_member_wage_require+"Status"))
	dataRet.ChangeType = int(myredis.GetUserFieldInt64NoSelect(uid, g_tbl_member_wage_require+"ChangeType"))
	dataRet.AddTime = myredis.GetUserFieldString64NoSelect(uid, g_tbl_member_wage_require+"AddTime")
	return dataRet
}
func LoadUserWage(uid string) {
	sqlSelect := fmt.Sprintf("SELECT ID,CONVERT(AddTime,CHAR) as AddTime , uid,ChangeMoney,NeedWageRequire,CurWageRequire,Status,ChangeType FROM tbl_member_wage_require "+
		"WHERE uid=%s and status = 0 and NeedWageRequire>0.00 order by ID asc limit 1", uid)

	var memWageRequire MemberWageRequire
	errGet := g_sql.Get(&memWageRequire, sqlSelect)

	if errGet == nil {
		myredis.SetUserFieldValueByInt64(uid, g_tbl_member_wage_require+"ID", memWageRequire.ID)
		myredis.SetUserFieldValueByFloat64(uid, g_tbl_member_wage_require+"ChangeMoney", memWageRequire.ChangeMoney)
		myredis.SetUserFieldValueByFloat64(uid, g_tbl_member_wage_require+"NeedWageRequire", memWageRequire.NeedWageRequire)
		myredis.SetUserFieldValueByFloat64(uid, g_tbl_member_wage_require+"CurWageRequire", memWageRequire.CurWageRequire)
		myredis.SetUserFieldValueByInt(uid, g_tbl_member_wage_require+"Status", memWageRequire.Status)
		myredis.SetUserFieldValueByInt(uid, g_tbl_member_wage_require+"ChangeType", memWageRequire.ChangeType)
		myredis.SetUserFieldValue(uid, g_tbl_member_wage_require+"AddTime", memWageRequire.AddTime)
	} else {
		if errGet.Error() != "sql: no rows in result set" {
			helper.SqlSelectErrLog("%s\n%s", sqlSelect, errGet.Error())
		}

		myredis.SetUserFieldValueByInt64(uid, g_tbl_member_wage_require+"ID", 0)
		myredis.SetUserFieldValueByFloat64(uid, g_tbl_member_wage_require+"ChangeMoney", 0.00)
		myredis.SetUserFieldValueByFloat64(uid, g_tbl_member_wage_require+"NeedWageRequire", 0.00)
		myredis.SetUserFieldValueByFloat64(uid, g_tbl_member_wage_require+"CurWageRequire", 0.00)
		myredis.SetUserFieldValueByInt(uid, g_tbl_member_wage_require+"Status", 0)
	}

	sqlSelect = fmt.Sprintf("SELECT ID, CONVERT(AddTime,CHAR) as AddTime, uid,ChangeMoney,NeedWageRequire,CurWageRequire,Status ,ChangeType FROM tbl_member_wage_require "+
		"WHERE uid=%s and status = 0 and ID!=%d and NeedWageRequire>0.00 order by ID asc limit 1", uid, memWageRequire.ID)

	var memWageNext MemberWageRequire
	errGet = g_sql.Get(&memWageNext, sqlSelect)

	if errGet == nil {
		myredis.SetUserFieldValueByInt64(uid, g_tbl_member_wage_require_next+"ID", memWageNext.ID)
		myredis.SetUserFieldValueByFloat64(uid, g_tbl_member_wage_require_next+"ChangeMoney", memWageNext.ChangeMoney)
		myredis.SetUserFieldValueByFloat64(uid, g_tbl_member_wage_require_next+"NeedWageRequire", memWageNext.NeedWageRequire)
		myredis.SetUserFieldValueByFloat64(uid, g_tbl_member_wage_require_next+"CurWageRequire", memWageNext.CurWageRequire)
		myredis.SetUserFieldValueByInt(uid, g_tbl_member_wage_require_next+"Status", memWageNext.Status)
		myredis.SetUserFieldValueByInt(uid, g_tbl_member_wage_require_next+"ChangeType", memWageRequire.ChangeType)
		myredis.SetUserFieldValue(uid, g_tbl_member_wage_require_next+"AddTime", memWageRequire.AddTime)
	} else {
		if errGet.Error() != "sql: no rows in result set" {
			helper.SqlSelectErrLog("%s\n%s", sqlSelect, errGet.Error())
		}

		myredis.SetUserFieldValueByInt64(uid, g_tbl_member_wage_require_next+"ID", 0)
		myredis.SetUserFieldValueByFloat64(uid, g_tbl_member_wage_require_next+"ChangeMoney", 0.00)
		myredis.SetUserFieldValueByFloat64(uid, g_tbl_member_wage_require_next+"NeedWageRequire", 0.00)
		myredis.SetUserFieldValueByFloat64(uid, g_tbl_member_wage_require_next+"CurWageRequire", 0.00)
		myredis.SetUserFieldValueByInt(uid, g_tbl_member_wage_require_next+"Status", 0)
	}
}

/*
增加玩家打码变化的记录
*/
func AddUserWageItem(uid string, ChangeMoney float64, TransactionType int) {

	channnelId, _ := strconv.Atoi(GetMemberOperatorId(uid))
	NeedWageRequire := ChangeMoney * myConfig.GetFlowMul(channnelId, TransactionType)

	if TransactionType == helper.AdminAddWagedOnly {
		NeedWageRequire = ChangeMoney
	}

	if NeedWageRequire == 0.00 {
		//不需要打码
		AddAgencyAmount(uid, math.Abs(ChangeMoney))
		return
	}
	sqlSelect := fmt.Sprintf("insert into  tbl_member_wage_require(uid,ChangeMoney,NeedWageRequire,CurWageRequire,Status,AddTime,WageFinishTime,WageFinishWay,ChangeType) "+
		"values(%s,%0.2f,%0.2f,0.00,0,'%s','%s',0,%d)", uid, ChangeMoney, NeedWageRequire,
		time.Now().Format("2006-01-02 15:04:05"),
		time.Now().Format("2006-01-02 15:04:05"),
		TransactionType)
	_, err := g_sql.Exec(sqlSelect)
	if err != nil {
		helper.GetloggerInstance().Emergencyf("%s\n%s", sqlSelect, err.Error())
	}

	UserCurRequire := myredis.GetUserFieldFloat64NoSelect(uid, g_tbl_member_wage_require+"NeedWageRequire")
	if UserCurRequire == 0.0 {
		LoadUserWage(uid)
	}
}

// 后台手动上分添加打码
func AddUserWageManual(uid string, ChangeMoney float64, times float64) {

	NeedWageRequire := ChangeMoney * times
	if NeedWageRequire == 0.00 {
		//不需要打码
		AddAgencyAmount(uid, math.Abs(ChangeMoney))
		return
	}
	sqlSelect := fmt.Sprintf("insert into  tbl_member_wage_require(uid,ChangeMoney,NeedWageRequire,CurWageRequire,Status,AddTime,WageFinishTime,WageFinishWay) "+
		"values(%s,%0.2f,%0.2f,0.00,0,'%s','%s',0)", uid, ChangeMoney, NeedWageRequire, time.Now().Format("2006-01-02 15:04:05"), time.Now().Format("2006-01-02 15:04:05"))
	_, err := g_sql.Exec(sqlSelect)
	if err != nil {
		helper.GetloggerInstance().Emergencyf("%s\n%s", sqlSelect, err.Error())
	}

	UserCurRequire := myredis.GetUserFieldFloat64NoSelect(uid, g_tbl_member_wage_require+"NeedWageRequire")
	if UserCurRequire == 0.0 {
		LoadUserWage(uid)
	}
}

/*
保存玩家的打码量
*/
func SaveUserWageRequire(uid string) {
	CurWageRequire := myredis.GetUserFieldFloat64NoSelect(uid, g_tbl_member_wage_require+"CurWageRequire")
	NeedWageRequire := myredis.GetUserFieldFloat64NoSelect(uid, g_tbl_member_wage_require+"NeedWageRequire")
	ID := myredis.GetUserFieldInt64NoSelect(uid, g_tbl_member_wage_require+"ID")
	if ID == 0 {
		return
	}

	sqlSelect := fmt.Sprintf("update  tbl_member_wage_require set CurWageRequire=%0.2f,NeedWageRequire=%0.2f where uid=%s and ID=%d and Status=0",
		CurWageRequire, NeedWageRequire, uid, ID)
	_, err := g_sql.Exec(sqlSelect)
	if err != nil {
		helper.GetloggerInstance().Emergencyf("%s\n%s", sqlSelect, err.Error())
	}

	//save next waged required

	CurWageRequire = myredis.GetUserFieldFloat64NoSelect(uid, g_tbl_member_wage_require_next+"CurWageRequire")
	NeedWageRequire = myredis.GetUserFieldFloat64NoSelect(uid, g_tbl_member_wage_require_next+"NeedWageRequire")
	ID = myredis.GetUserFieldInt64NoSelect(uid, g_tbl_member_wage_require_next+"ID")
	if ID == 0 {
		return
	}

	sqlSelect = fmt.Sprintf("update  tbl_member_wage_require set CurWageRequire=%0.2f,NeedWageRequire=%0.2f where uid=%s and ID=%d",
		CurWageRequire, NeedWageRequire, uid, ID)
	_, err = g_sql.Exec(sqlSelect)
	if err != nil {
		helper.GetloggerInstance().Emergencyf("%s\n%s", sqlSelect, err.Error())
	}

}

func ClearUserWagedRequire(uid string) {
	NeedWageRequire := myredis.GetUserFieldFloat64NoSelect(uid, g_tbl_member_wage_require+"NeedWageRequire")
	CurWageRequire := myredis.GetUserFieldFloat64NoSelect(uid, g_tbl_member_wage_require+"CurWageRequire")

	unFinishRequire := NeedWageRequire - CurWageRequire
	AddUserWageRequire(uid, unFinishRequire, 0)
}

/*
增加玩家的打码量
*/
func AddUserWageRequire(uid string, AddCurWageAmount float64, AddNeedWagedAmount float64) {

	LoadUserToRedis(uid)
	NeedWageRequire := myredis.GetUserFieldFloat64NoSelect(uid, g_tbl_member_wage_require+"NeedWageRequire")
	if NeedWageRequire == 0.0 {
		//所有打码任务都已经完成
		brl := GetBalanceFloat64ByUid(uid)
		SetUnlockAmount(uid, brl)
		SetAgencyAmount(uid, brl)
		return
	}

	CurWageRequire := myredis.GetUserFieldFloat64NoSelect(uid, g_tbl_member_wage_require+"CurWageRequire")
	NeedWageRequire += AddNeedWagedAmount
	if CurWageRequire+AddCurWageAmount >= NeedWageRequire {
		//更新打码的记录
		SaveUserWageRequire(uid)
		ID := myredis.GetUserFieldInt64NoSelect(uid, g_tbl_member_wage_require+"ID")
		sqlSelect := fmt.Sprintf("update  tbl_member_wage_require set CurWageRequire=%0.2f,NeedWageRequire=%0.2f, status=1,WageFinishTime='%s' "+
			"where uid=%s and ID=%d", NeedWageRequire, NeedWageRequire, time.Now().Format("2006-01-02 15:04:05"), uid, ID)
		_, errUpdate := g_sql.Exec(sqlSelect)
		if errUpdate != nil {
			helper.GetloggerInstance().Emergencyf("%s\n%s", sqlSelect, errUpdate.Error())
		}

		//增加可提额度
		ChangeMoney := myredis.GetUserFieldFloat64NoSelect(uid, g_tbl_member_wage_require+"ChangeMoney")
		AddUnlockAmount(uid, ChangeMoney)
		AddAgencyAmount(uid, ChangeMoney)
		//重新加载一条新的打码任务
		leftWage := CurWageRequire + AddCurWageAmount - NeedWageRequire

		for {
			LoadUserWage(uid)
			NewID := myredis.GetUserFieldInt64NoSelect(uid, g_tbl_member_wage_require+"ID")

			if NewID == 0 {
				brl := GetBalanceFloat64ByUid(uid)
				SetUnlockAmount(uid, brl)
				SetAgencyAmount(uid, brl)
				break
			}

			NewNeedWageRequire := myredis.GetUserFieldFloat64NoSelect(uid, g_tbl_member_wage_require+"NeedWageRequire")
			if NewNeedWageRequire == 0.0 {
				break
			}

			if leftWage >= NewNeedWageRequire {
				sqlSelect := fmt.Sprintf("update  tbl_member_wage_require set CurWageRequire=%0.2f,NeedWageRequire=%0.2f, status=1,WageFinishTime='%s' "+
					"where uid=%s and ID=%d", NewNeedWageRequire, NewNeedWageRequire, time.Now().Format("2006-01-02 15:04:05"), uid, NewID)
				_, errUpdate := g_sql.Exec(sqlSelect)
				if errUpdate != nil {
					helper.GetloggerInstance().Emergencyf("%s\n%s", sqlSelect, errUpdate.Error())
					break
				} else {
					//增加可提额度
					ChangeMoney := myredis.GetUserFieldFloat64NoSelect(uid, g_tbl_member_wage_require+"ChangeMoney")
					AddUnlockAmount(uid, ChangeMoney)
					AddAgencyAmount(uid, ChangeMoney)
					leftWage -= NewNeedWageRequire
				}
			} else {
				myredis.AddUserFieldValueByFloat64(uid, g_tbl_member_wage_require+"CurWageRequire", leftWage)
				break
			}
		}
	} else {
		myredis.AddUserFieldValueByFloat64(uid, g_tbl_member_wage_require+"CurWageRequire", AddCurWageAmount)
		myredis.AddUserFieldValueByFloat64(uid, g_tbl_member_wage_require+"NeedWageRequire", AddNeedWagedAmount)
	}
}

/*
计算流水
*/
func CalcValidRunning(uid string, winAmount float64, betAmount float64) float64 {
	return betAmount
}

/*
计算有效打码 用来打码
*/
func CalcValidWaged(uid string, strPlatformId string, winAmount float64, betAmount float64) float64 {
	/*
		gameType := myConfig.FindGameType(gameId)
		if gameType == 3 {
			return betAmount
		}
	*/

	var gameValidRunning float64
	if strPlatformId == helper.PPVideo || strPlatformId == helper.EvoVideo || strPlatformId == helper.PPlive || strPlatformId == helper.Evolution {
		realWinAmount := math.Abs(winAmount - betAmount)
		gameValidRunning = math.Min(realWinAmount, betAmount)
	} else {
		gameValidRunning = betAmount
	}

	var betValidRunning float64 //有效打码比例换算
	betValidRunning = GetValidWagedFlowMultiple(uid, gameValidRunning) * gameValidRunning

	return betValidRunning
}

/*
游戏过程中触发加码
*/
func AddGameWaged(Uid string, gameWin float64, gameBet float64) {

	realWinAmount := gameWin - gameBet
	wageMul := myConfig.GetWageMulByBetMul(realWinAmount)
	addNeedWaged := wageMul * (realWinAmount)
	if wageMul > 0.00 {
		nextWageId := myredis.GetUserFieldFloat64NoSelect(Uid, g_tbl_member_wage_require_next+"ID")
		if nextWageId == 0 {
			AddUserWageRequire(Uid, 0, addNeedWaged)
		} else {
			myredis.AddUserFieldValueByFloat64(Uid, g_tbl_member_wage_require_next+"NeedWageRequire", addNeedWaged)
		}
		helper.GetloggerInstance().Infof("AddGameWaged:%s gameWin:%0.0f,gameBet:%0.2f wageMul:%0.2f", Uid, gameWin, gameBet, wageMul)
	}
}

/*
加码操作正常应该增加到当前进行的打码任务的下一条任务中
*/
func AdminAddUserWageRequire(uid string, AddCurWageAmount float64, AddNeedWagedAmount float64) {
	LoadUserToRedis(uid)
	nextWageId := myredis.GetUserFieldFloat64NoSelect(uid, g_tbl_member_wage_require_next+"ID")
	if nextWageId == 0 {
		AddUserWageRequire(uid, AddCurWageAmount, AddNeedWagedAmount)
	} else {
		myredis.AddUserFieldValueByFloat64(uid, g_tbl_member_wage_require_next+"NeedWageRequire", AddNeedWagedAmount)
		myredis.AddUserFieldValueByFloat64(uid, g_tbl_member_wage_require_next+"CurWageRequire", AddCurWageAmount)
	}
}
